package com.example.learn;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.example.learn.http.CommonCallback;
import com.example.learn.http.CommonHttp;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.engine.ImageEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnImageCompleteCallback;
import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private AppCompatImageView backImageView = null;
    private AppCompatImageView goImageView = null;
    private AppCompatImageView refreshImageView = null;
    private AppCompatImageView favImageView = null;
    private AppCompatImageView memberImageView = null;
    private AppCompatImageView sendImageView = null;
    private AppCompatEditText linkEditText = null;
    private SwipeRefreshLayout mainSwipeRefreshLayout = null;
    private WebView mainWebView = null;
    private ContentLoadingProgressBar mainProgressBar = null;

    public static boolean isLogin = false;
    public static CommonHttp commonHttp = null;
    public static SharedPreferences sharedPreferences = null;
    public static SharedPreferences.Editor editor = null;

    @SuppressLint({"SetJavaScriptEnabled", "CommitPrefEdits"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        backImageView = findViewById(R.id.backImageView);
        goImageView = findViewById(R.id.goImageView);
        refreshImageView = findViewById(R.id.refreshImageView);
        favImageView = findViewById(R.id.favImageView);
        memberImageView = findViewById(R.id.memberImageView);
        sendImageView = findViewById(R.id.sendImageView);
        linkEditText = findViewById(R.id.linkEditText);
        mainSwipeRefreshLayout = findViewById(R.id.mainSwipeRefreshLayout);
        mainWebView = findViewById(R.id.mainWebView);
        mainProgressBar = findViewById(R.id.mainProgressBar);

        sharedPreferences = getSharedPreferences("Test", MODE_PRIVATE);
        editor = sharedPreferences.edit();

        //初始化我们自行封装的okgo
        commonHttp = new CommonHttp(getApplication(), Common.API_URL, sharedPreferences.getString("token", ""));

        //初始化OKGO,给它添加一个公共的参数token
        // ctrl + shift + r
        HttpParams httpParams = new HttpParams();
        httpParams.put("token", sharedPreferences.getString("token", ""));
        OkGo.getInstance().addCommonParams(httpParams).init(getApplication());

        //是否登录
        String token = sharedPreferences.getString("token", "");
        isLogin = !token.isEmpty();
        if (isLogin) {
            commonHttp.post("member/getData/", null, new CommonCallback() {
                @Override
                public void onSuccess(String data) {

                }

                @Override
                public void onFailure(String msg) {
                    //请求失败,代表token已失效...

                }
            });
        }

        mainSwipeRefreshLayout.setColorSchemeColors(
                getResources().getColor(R.color.colorAccent),
                getResources().getColor(R.color.colorPrimaryDark),
                getResources().getColor(R.color.colorPrimary)
        );

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mainWebView.loadUrl(Objects.requireNonNull(linkEditText.getText()).toString());

        mainWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                linkEditText.setText(url);
                mainWebView.loadUrl(url);
                return true;
            }
        });

        mainWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                mainProgressBar.setVisibility(View.VISIBLE);
                mainProgressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    mainProgressBar.setVisibility(View.GONE);
                }
            }
        });

        backImageView.setOnClickListener(v -> {
            mainWebView.goBack();//后退
        });

        goImageView.setOnClickListener(v -> {
            mainWebView.goForward();//前进
        });

        refreshImageView.setOnClickListener(v -> {
            mainWebView.reload();//重新加载
        });

        favImageView.setOnClickListener(v -> {
            //第一步：构建数据
            HttpParams httpParams1 = new HttpParams();
            httpParams1.put("title", mainWebView.getTitle());
            httpParams1.put("link", mainWebView.getUrl());
            //第二步：请求addtags接口
            commonHttp.post("member/addTags/", httpParams1, new CommonCallback() {
                @Override
                public void onSuccess(String data) {
                    Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(String msg) {
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            });
        });

        favImageView.setOnLongClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, TagsActivity.class);
            intent.putExtra("test", "这是从MainActivity传过来的数据~");
            startActivityForResult(intent, 999);
            return false;
        });

        memberImageView.setOnClickListener(view -> {
            if (isLogin) {

               /* Toast.makeText(MainActivity.this, "您已登录", Toast.LENGTH_SHORT).show();*/
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(new ImageEngine() {

                            @Override
                            public void loadImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView) {
                                Glide.with(MainActivity.this).load(url).into(imageView);

                            }

                            @Override
                            public void loadImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, SubsamplingScaleImageView longImageView, OnImageCompleteCallback callback) {
                                Glide.with(MainActivity.this).load(url).into(imageView);
                            }

                            @Override
                            public void loadImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, SubsamplingScaleImageView longImageView) {
                                Glide.with(MainActivity.this).load(url).into(imageView);
                            }

                            @Override
                            public void loadFolderImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView) {
                                Glide.with(MainActivity.this).load(url).into(imageView);
                            }

                            @Override
                            public void loadAsGifImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView) {
                                Glide.with(MainActivity.this).load(url).into(imageView);
                            }

                            @Override
                            public void loadGridImage(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView) {
                                Glide.with(MainActivity.this).load(url).into(imageView);

                            }
                        })
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                return;
            }
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
        });

        sendImageView.setOnClickListener(v -> {
            //mainWebView.loadUrl(Objects.requireNonNull(linkEditText.getText()).toString());
            startActivity(new Intent(this, MainActivity.class));
        });

        mainSwipeRefreshLayout.setOnRefreshListener(() ->
                new Handler().postDelayed(() -> {
                    mainSwipeRefreshLayout.setRefreshing(false);
                    mainWebView.reload();
                }, 3000)
        );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断页面是不是正常返回
        if (resultCode == RESULT_OK) {
            //判断是不是自己做的标识
            if (requestCode == 999) {
                //判断数据是不是空
                if (data != null) {
                    mainWebView.loadUrl(data.getStringExtra("url"));
                }
                return;
            }
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                Log.d("TAGS",list.get(0).getPath());
                //可以拿到文件路径
                HttpParams httpParams = new HttpParams();
                httpParams.put("file",new File(list.get(0).getPath()));
                //请求接口
                commonHttp.post("member/upload/", httpParams, new CommonCallback() {
                    @Override
                    public void onSuccess(String data) {
                        Toast.makeText(MainActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                    }


                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

}
